<?php
namespace Common\Model;

use Think\Model;

class FollowUserModel extends Model
{
    /**
     * 统计关注和粉丝
     *
     * @param string $uid
     * @param string $type
     * @return mixed
     */
    public function get_follow_count($uid = '', $type = '1')
    {
        $uid = intval($uid);
        if ($type == '1') {
            $map['uid'] = $uid;
        } else {
            $map['yuid'] = $uid;
        }
        $n = $this->where($map)->count();
        return $n;
    }

    /**
     * 获取列表
     *
     * @param string $map
     * @param bool $page
     * @param int $limit
     * @return mixed
     */
    public function get_list($map = '', $page = true, $limit = 10)
    {
        if ($page) {
            $count = $this->where($map)->count();
            $Page = pager($count, limit);
            $result = $this->where($map)->order('id DESC')->limit($Page->firstRow . ',' . $Page->listRows)->select();
        } else {
            $result = $this->where($map)->order('id DESC')->limit($limit)->select();
        }
        $myuid = session('ytata.uid');
        foreach ($result as $key => $v) {

            if (!empty($map['uid'])) {
                $v['user'] = D('User')->get_user_one($v['yuid'], true, 1);
            } else {
                $v['user'] = D('User')->get_user_one($v['uid'], true, 1);
            }
            if (!empty($myuid)) {
                $chenk = $this->chenk_follow_user($myuid, $v['user']['uid']);
                if ($chenk) {
                    $v['user']['is_follow'] = 1;
                }
            }
            $list[] = $v;
        }
        $return['list'] = $list;
        $return['count'] = $page ? $count : count($list);
        $return['page'] = $page ? $Page->fshow() : '';
        return $return;
    }

    /**
     * 检测是否关注过
     *
     * @param string $uid
     * @param string $yuid
     * @return bool
     */
    public function chenk_follow_user($uid = '', $yuid = '')
    {
        $map['uid'] = intval($uid);
        $map['yuid'] = intval($yuid);
        $n = $this->where($map)->count();
        if ($n) {
            return true;
        }
        return false;
    }

    /**
     * 关注用户
     *
     * @param string $uid
     * @param string $yuid
     * @return bool
     */
    public function follow_user($uid = '', $yuid = '')
    {
        $data['uid'] = intval($uid);
        $data['yuid'] = intval($yuid);
        $data['addtime'] = time();
        $this->add($data);
        return true;
    }

    /**
     * 取消关注
     *
     * @param string $uid
     * @param string $yuid
     * @return bool
     */
    public function clear_follow_user($uid = '', $yuid = '')
    {
        $map['uid'] = intval($uid);
        $map['yuid'] = intval($yuid);
        $this->where($map)->delete();
        return true;
    }

}